<?php
namespace app\mini\controller;

use think\Controller;
use app\mini\model\Member as Members;
use app\mini\model\Project;
use app\mini\validate\authValidate;
use app\mini\validate\rechargeValidate;
use app\index\model\OrderProfit;
use app\index\model\Order as orders;
use app\index\model\Mobilelog;
use app\index\model\Notice;
use app\index\model\Lookinto;
use app\index\model\Invest;
use app\index\model\Question;
use app\index\model\Bankcode;
use app\index\model\Card;
use app\index\model\Recharge;
use app\index\model\Putlog;
use app\index\model\Getcash;
use think\Session;
use think\Db;
use think\Request;
use expand\BestSignDemo;
use expand\Yunst;
use expand\YunPay;
use think\Config;
use redis\Redis;

class Member extends Common
{
    const PERPAGE = 10;
    public function _initialize(){
        parent::_initialize();
        if(session('user_id')){
            $mModel = new Members;
            $member = $mModel->where(['id'=>session('user_id')])->find();
            if($member['is_check'] == 1 && !$member['task_id']){
                $credential= ['identity'=>$member['certificate']];
                $this->ToBsetSign($member['username'],$member['mobile'],$credential);

                $redis = Redis::instance();
                $token = $redis->get('front_user:' . session('user_id'));
                $member['modify'] = true;
                $redis->hSet('user_info', $token, json_encode($member));
            }
            if($member['is_check'] == 1 && !$member['bizUserId']){
                $this->CreateYST();

                $redis = Redis::instance();
                $token = $redis->get('front_user:' . session('user_id'));
                $member['modify'] = true;
                $redis->hSet('user_info', $token, json_encode($member));
            }
        }

    }

    /**
     * 个人中心首页
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     */
    public function index(Request $request){
        $mModel = new Members();
        $NoModel = new Notice();
        $user_info = $request->user_info;
        $uid = $user_info['id'];
        if(empty($user_info)){
            outPutData('','未查询到会员信息',Config::get('code.tipsCode'));
        }
        $my_data = $mModel->where(array('id'=>$uid))->field('mobile,money,sex,is_check,signContract,username,head_thumb,safeMobile,pay_password,yunmobile')->find()->toArray();
        $user_info['money'] = $my_data['money'];
        $user_info['mobile_show'] = getXXtel($user_info['mobile']);
        if(count(explode($my_data['head_thumb'],'/Public/upload/head/'))>1){
            $user_info['head_thumb'] = '';
        }
        if(count(explode($my_data['head_thumb'],'/uploads/headimg/'))==0){
            $user_info['head_thumb'] = '/uploads/headimg/'. $user_info['head_thumb'];
        }

        $lookintoModel = new Lookinto();
        $lookInfo = $lookintoModel->where(['uid' => $user_info['id']])->order('create_time desc')->limit(1)->find();
        $lookInfo = empty($lookInfo) ? array() : $lookInfo->toArray();
        if (empty($lookInfo)){
            $user_info['member_type'] = '';
        } else {
            $user_info['member_type'] = $lookInfo['name'];
        }
        $notice_num = $NoModel->where(array('uid'=>$uid,'isread'=>0))->count();
        if(!empty($user_info['is_vip'])){
            $res_data['is_vip'] = $user_info['is_vip'];
        }else{
            $res_data['is_vip'] = $mModel->checkMemberVip($uid);
            $redis = Redis::instance();
            $token = $redis->get('front_user:' . session('user_id'));
            $user_info['is_vip'] = $res_data['is_vip'];
            $redis->hSet('user_info', $token, json_encode($user_info));
        }

        $res_data['invite'] = $user_info['invite'];
        $res_data['head_thumb']=$user_info['head_thumb'];
        $res_data['username']=$user_info['username'];
        $res_data['mobile_show']=$user_info['mobile_show'];
        $res_data['mobile']=$my_data['mobile'];
        $res_data['money']=$user_info['money'];
        $res_data['notice_num']=$notice_num;
        $res_data['member_type'] = $user_info['member_type'];
        $res_data['sex'] = $my_data['sex'];
        $res_data['is_check'] = $my_data['is_check'];
        $res_data['is_sign'] = empty($my_data['signContract']) ? 1 : 2; // 1 未签约 2 已签约
        $res_data['safeMobile'] = $my_data['safeMobile'];
        $res_data['pay_password'] = !empty($my_data['pay_password']) ? 1 : 0;
        $res_data['yunmobile'] = $my_data['yunmobile'];
        outPutData($res_data);
    }


    /**
     * 个人实名认证
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     */
    public function authentication(Request $request){
        $user_info = $request->user_info;
        $uid = $user_info['id'];
        $mModel = new Members();
        $param = $request->param();
        if(request()->isPost() && !empty($param['certificate'])){
            $validate = new authValidate();
            if(!($validate->check($param))){
                outPutData('',$validate->getError(),Config::get('code.tipsCode'));
            }
            $YunClass = new Yunst();
            $certificate=$param['certificate'];
            $re=$mModel->where(['certificate'=>$certificate,'is_check'=>1])->value('id');
            if($re>1){
                outPutData('','用户个人信息已经在其他账户下实名',Config::get('code.tipsCode'));
            }
            if($param['mobile_code'] != session('mobile_code')){
                $content = date('Y-m-d H:i:s').':用户手机号'.$param['bank_mobile'].'手机验证码不正确。';
                file_put_contents(date("Y-m-d H").'sendCode.txt',$content.PHP_EOL,FILE_APPEND);
                outPutData('','手机验证码不正确',Config::get('code.tipsCode'));
            }
            $mobile=$mModel->where(['id'=>$uid])->value('mobile');
            $bizUserId = 'hry'.$mobile;
            $res1=$YunClass->createMember($bizUserId);  //云商通创建会员 by hey
            $rut=$this->smrz($param);  // 云商通个人实名认证 by hey
            if($rut['status']=='OK'){
                $code=$mModel->where(['id'=>$uid])->value('certificate');
                if(empty($code)){
                    if($res1['status']=='OK'){
                        $mModel->where(['id'=>$uid])->update(['username'=>$param['username'],'certificate'=>$param['certificate'],'bizUserId'=>$bizUserId]);
                    }else{
                        $mModel->where(['id'=>$uid])->update(['username'=>$param['username'],'certificate'=>$param['certificate']]);
                    }
                }
                $member = $mModel->where(['id'=>$uid])->find();
                $credential= ['identity'=>$member['certificate']];
                $this->ToBsetSign($member['username'],$member['mobile'],$credential);   //上上签用户注册  by hey
                $res = $mModel->where(['id'=>$uid])->update(['is_check'=>'1','ssqmobile'=>$mobile]);
                if($res){
                    $data['sex'] = get_sex($param['certificate']);
                    $data['ask'] = get_age($param['certificate']);
                    unset($data['mobile_code']);
                    $res1 = $mModel->where(['id'=>$uid])->update(array('sex'=>$data['sex'],'ask'=>$data['ask']));
                    if(!$res1){
                        $error['uid'] = $uid;
                        $error['sex'] = $data['sex'];
                        $error['ask'] = $data['ask'];
                        $error['error'] = '实名认证更新性别与年龄出错';
                        file_put_contents(date("Y-m-d H:i").'sex_auth.txt',json_encode($error,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
                    }
                    $member = $mModel->where(['id'=>$uid])->find();
                    session('userName',$member['username']);
                    session('isCheck',1);
                }
                $redis = Redis::instance();
                $token = $redis->get('front_user:' . $user_info['id']);
                $user_info['modify'] = true;
                $redis->hSet('user_info', $token, json_encode($user_info));
                $res_data=array('msg'=>'认证成功');
                outPutData($res_data);
            }else{
                outPutData('',$rut['message'],Config::get('code.tipsCode'));
            }
        }
        $res_data =$user_info;
        outPutData($res_data);

    }

    /**
     * 云商通实名
     * @param  $data
     * @author hey_heyang(635870453@qq.com)
     * @return mixed
     */
    private function smrz($data){
        $user_info = Request()->user_info;
        $YunClass = new Yunst();
        $mModel  = new Members();
        $mobile=$mModel->where(['id'=>$user_info['id']])->value('mobile');
        $bizUserId = 'hry'.trim($mobile);
        $username=trim($data['username']);
        $certificate=trim($data['certificate']);
        $rut=$YunClass->setRealName($bizUserId,$username,$certificate);
        return $rut;
    }

    /**
     * 发送验证码
     *  @param Request $request
     * @author hey_heyang(635870453@qq.com)
     */
    public function sendcode(Request $request){
        if(request()->isPost()){
            $Mobilelog=new Mobilelog();
            $param = $request->param();
            $mobile = trim($param['mobile']);
            $old=$Mobilelog->where(['oldmobile'=>$mobile])->find();
            if(!empty($old)){
                outPutData('','该手机号已被系统注销',Config::get('code.tipsCode'));
            }
            $code = Session::get('code');
            if (strtolower($code) != strtolower(trim($param['code']))) {
                outPutData('','图形验证码输入错误',Config::get('code.tipsCode'));
            }
            $code = rand(1000,9999);
            $res = SmsSend($mobile,$code);
            if($res['code'] == 0){
                session('mobile_code',$code);
                $res = array('msg'=>'发送成功');
                outPutData($res);
            }else{
                outPutData('',$res['detail'],Config::get('code.tipsCode'));
            }
        }
    }

    /**
     * 上上签注册个人用户
     * @param $name
     * @param $mobile
     * @param $credential
     * @author hey_heyang(635870453@qq.com)
     * return string
     */
    private function ToBsetSign($name,$mobile,$credential){
        $bestSign_demo = new BestSignDemo();
        $mModel  = new Members();
        $user_info = Request()->user_info;
        $account = $mobile;
        $user_type = "1";
        $response = $bestSign_demo->regUser($account,$mobile, $name, $user_type, $credential,1);
        if(empty($user_info)){
            $user_info['id'] = session('user_id');
        }
        if($response->errno == 0){
            $content = date('Y-m-d H:i:s').':用户手机号'.$mobile.'身份证检查通过,taskId:'.$response->data->taskId.'。';
            file_put_contents(date("Y-m-d H").'auth.txt',$content.PHP_EOL,FILE_APPEND);
            $mModel->where(['id'=>$user_info['id']])->update(['task_id'=>$response->data->taskId]);
            return $response->data->taskId;
        }else{
            $content = date('Y-m-d H:i:s').':用户手机号'.$mobile.'身份证检查通过,taskId:'.$response->data->taskId.'。';
            file_put_contents(date("Y-m-d H").'auth.txt',$response->errmsg.'*****'.$content.PHP_EOL,FILE_APPEND);
            return $response->errmsg;
        }
    }


    //云商通-创建会员/实名认证
    private function CreateYST(){
        $YunClass = new Yunst();
        $mModel  = new Members();
        $Minfo = $mModel->where(['id'=>session('user_id')])->find();
        $bizUserId = 'hry'.$Minfo['mobile'];
        $res = $YunClass->createMember($bizUserId);
        if($res['status'] == 'OK'){
            $signedValue = json_decode($res['signedValue'],true);
            $mModel->where(['id'=>session('user_id')])->update(['YstId'=>$signedValue['userId'],'bizUserId'=>$signedValue['bizUserId']]);
            return $YunClass->setRealName($bizUserId,$Minfo['username'],$Minfo['certificate']);
        }elseif($res['message'] == '所属应用下已经存在此用户'){
            $mModel->where(['id'=>session('user_id')])->update(['bizUserId'=>$bizUserId]);
            $YunClass->setRealName($bizUserId,$Minfo['username'],$Minfo['certificate']);
        }
    }



    /**
     * 投资类型问卷数据
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getLookIntoData(Request $request){
        if($request->isPost()){
            $user_info = $request->user_info;
            $InvestModel = new Invest();
            $QuestModel = new Question();
            $title = $InvestModel->where(['id'=>3,'is_disable'=>1])->value('title');

            $dataList = $QuestModel->where(['jid'=>3,'is_check'=>1])->order('id ASC')->select();

            foreach($dataList as &$v){
                $v['answer'] = Db::table('tf_answer')->where(['qid'=>$v['id'],'is_check'=>1])->order('id ASC')->select();
            }
            unset($v);
            $res['title'] = $title;
            $res['list'] = empty($dataList)?array():$dataList->toArray();
            $res['total_page'] = count($res['data_list']);
            outPutData($res);
        }

    }

    /**
     * 投资评估
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function assess(Request $request){
        if(request()->isPost()){
            $user_info = $request->user_info;
            $lookintoModel = new Lookinto();
            $param =$request->param();
            $data=explode('&',$param['assess_key']);
            $score = 0;
            $content=array();
            foreach($data as $k=>$v){
                $res=explode('=',$v);
                $score += $res[1];
                $content[$res[0]]=$res[1];
            }
            $LookName = $this->getLookName($score);
            $insertData = [
                'uid' =>$user_info['id'],
                'aid' => 3,
                'content' => serialize($content),
                'score' => $score,
                'create_time' => time(),
                'name'	=> $LookName
            ];
            $res = $lookintoModel->insert($insertData);
            if($res){
                outPutData(array('msg'=>'恭喜!您是一位'.$LookName.'的投资人','member_type'=>$LookName));
            }else{
                outPutData('',$lookintoModel->getError(),Config::get('code.tipsCode'));
            }
        }
    }

//    /**
//     * 我的余额
//     * @param Request $request
//     * @author hey_heyang(635870453@qq.com)
//     */
//    public function myMoney(Request $request){
//        $user_info = $request->user_info;
//        $mModel= new Members();
//        $my_money = $mModel->where(array('id'=>$user_info['id']))->value('money');
//        $user_info['money'] = $my_money;
//        $res=$user_info;
//        outPutData($res);
//    }

    /**
     * 充值页面获取银行卡列表
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     */
    public function recharge(Request $request){
        $user_info = $request->user_info;
        $param = $request->param();
        $CardModel = new Card();
        if($param['type']){
            $CardList = $CardModel->where(['user_id'=>$user_info['id'],'status'=>1,'cardType'=>['neq',2]])->select();
        }else{
            $CardList = $CardModel->where(['user_id'=>$user_info['id'],'status'=>1])->select();
        }

        $CardList = empty($CardList)?array():$CardList->toArray();
        if(count($CardList)){
            foreach($CardList as $k=>$v){
                $CardList[$k]['bank_number'] =  substr($v['bank_number'],0,4).'******'.substr($v['bank_number'],-4,4);
            }
        }
        $res=array('card_list'=>$CardList);
        outPutData($res);
    }


    /**
     * 快捷充值申请
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     */
    public function createOrder(Request $request){
        if(request()->isPost()){
            $CardModel = new Card();
            $RechargeModel = new Recharge();
            $user_info = $request->user_info;
            $uid = $user_info['id'];
            $param = $request->param();
            $validate = new rechargeValidate();
            if(!($validate->check($param))){
                outPutData('',$validate->getError(),Config::get('code.tipsCode'));
            }
            $mModel = new Members();
            $MemberInfo = $mModel->where(['id'=>$uid])->find();
            if(empty($MemberInfo['pay_password'])){
                outPutData('','未设置支付密码',Config::get('code.tipsCode'));
            }
            if(!password_verify($param['pay_password'],$MemberInfo['pay_password'])){
                outPutData('','支付密码不正确',Config::get('code.tipsCode'));
            }
            $CardInfo = $CardModel->where(['user_id'=>$uid,'id'=>$param['bank_id']])->find();
            $money = floatval($param['money']);
            if($money < confv('min-rechage')){
                outPutData('','充值金额最低不小于'.confv('min-rechage'),Config::get('code.tipsCode'));
            }
            $cvv=$CardInfo['cvv2'];
            if(!empty($cvv)){
                if($money>10000){
                    outPutData('','信用卡单笔充值不得超过一万元',Config::get('code.tipsCode'));
                }else{
                    $date1=date("Y-m");
                    $date2=date("Y-m",strtotime("+1 months"));
                    $summoney=$RechargeModel->where(['user_id'=>$uid,'status'=>2,'iscvv'=>2])->where('date','between time',[$date1,$date2])->sum('money');
                    $sumcount=$RechargeModel->where(['user_id'=>$uid,'status'=>2,'iscvv'=>2])->where('date','between time',[$date1,$date2])->count();
                    $ssm=($money+$summoney);
                    if($summoney>=10000){
                        outPutData('','信用卡充值金额已超过本月上限,请转用银行卡充值',Config::get('code.tipsCode'));
                    }elseif($ssm>10000){
                        outPutData('','当次充值金额与累计金额相加超过本月上限,请转用银行卡充值',Config::get('code.tipsCode'));
                    }elseif($sumcount>=4){
                        outPutData('','当月信用卡充值次数达到上限,请转用银行卡充值',Config::get('code.tipsCode'));
                    }
                }
                $iscvv=2;
            }else{
                $iscvv=1;
            }
            $fee = confv('fee');
            $feeto = $money < 200 ? 1 : round($fee / 100 * $money,2);
            $order = [
                'user_id' => $uid,
                'mobile'  => $CardInfo['bank_mobile'],
                'money'	=> $money,
                'fee'	=> $feeto,
                'order'	=> 'NO'.create_order(),
                'type'	=> 2,
                'status'=>0,
                'bankCardNo' => $CardInfo['bank_number'],
                'iscvv'=>$iscvv,
                'bankcard'=>$CardInfo['bank_number']
            ];

            $res = $RechargeModel->allowField(true)->save($order);
            if(!$res){
                outPutData('',$RechargeModel->getError(),Config::get('code.tipsCode'));
            }
            $YunClass = new Yunst();
            $message = $YunClass->createRech($user_info['bizUserId'],$order);  //云商通账户充值申请
            if($message['status'] != 'OK'){
                outPutData('',$message['message'],Config::get('code.tipsCode'));
            }
            $signedValue = json_decode($message['signedValue'],true);
            $RechargeModel -> where(['order'=>$signedValue['bizOrderNo']])->update(['status'=>1,'orderNo'=>$signedValue['orderNo'],'tradeNo'=>$signedValue['tradeNo']]);
            outPutData(array('msg'=>'请在三分钟内输入输入短信验证码','order_sn'=>$signedValue['bizOrderNo'],'order_id'=>$RechargeModel->id,'money'=>floatval($money+$feeto),'fee'=>$feeto,'time'=>date('Y-m-d H:i:s',time()),'mobile'=>$user_info['mobile']));
        }
    }

    /**
     * 获取充值订单详情
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     */
    public function getRorderInfo(Request $request){
        $rModel = new Recharge();
        $user_info = $request->user_info;
        $param = $request->param();
        if($request->isPost()) {
            if(empty($param['order_id'])){
                outPutData('','提交参数错误,请重新刷新页面',Config::get('code.tipsCode'));
            }
            $order_data = $rModel->where(array('id'=>intval($param['order_id']),'user_id'=> $user_info['id']))->find();
            $order_info = empty($order_data)?array():$order_data->toArray();
            if(empty($order_info)){
                outPutData('','未查询到订单信息',Config::get('code.tipsCode'));
            }
            $data['order_time'] = strtotime($order_info['date']);
            $data['current_time'] = time();
            $data['create_times'] = $order_info['date'];
            $data['fee'] = $order_info['fee'];
            $data['mobile'] = $user_info['mobile'];
            $data['order_sn'] = $order_info['order'];
            $data['money'] = floatval($order_info['money']+$order_info['fee']);
            $res['order_info'] = $data;
            outPutData($res);
        }

    }


    /**
     * 快捷充值确认支付
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     */
    public function surepay(Request $request){
        if(request()->isPost()){
            $user_info = $request->user_info;
            $param = $request->param();
            $order_sn = $param['order_sn'];
            $code = $param['code'];
            $payClass = new Yunst();
            $RechargeModel = new Recharge();
            $tradeNo = $RechargeModel->where(['order'=>$order_sn])->value('tradeNo');
            $res = $payClass->rechargePay($user_info['bizUserId'],$order_sn,$code,$tradeNo);
            if($res['status'] != 'OK'){
                outPutData('',$res['message'],Config::get('code.tipsCode'));
            }
            $signedValue = json_decode($res['signedValue'],true);
            if($signedValue['payStatus'] == 'fail'){
                outPutData('','充值失败',Config::get('code.tipsCode'));
            }
            if($signedValue['payStatus'] == 'pending'){
                outPutData('','充值进行中,请耐心等待',Config::get('code.tipsCode'));
            }
            outPutData(array('msg'=>'支付成功'));
        }
    }

    /**
     * 网关支付
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getWayPay(Request $request){
        if(request()->isPost()){
            $user_info = $request->user_info;
            $param = $request->param();
            $YunClass = new Yunst();
            $money = $param['money'];
            $bankCode = $param['bank_code'];
            if(floatval($money) < confv('min-rechage')){
                outPutData('','充值金额最低不小于'.confv('min-rechage'),Config::get('code.tipsCode'));
            }
            if(empty($bankCode)){
                outPutData('','请选择充值银行',Config::get('code.tipsCode'));
            }
            $fee = confv('fee');
            $fee = $money < 200 ? 1 : round($fee / 100 * $money,2);
            $order = [
                'user_id' => $user_info['id'],
                'money'	=> $money,
                'fee'	=> $fee,
                'order'	=> 'NO'.create_order(),
                'type'	=> 1,
                'status'=>0,
                'bankCode'=>$bankCode
            ];

            $RechargeModel = new Recharge();
            $res = $RechargeModel->allowField(true)->save($order);
            if(!$res){
                outPutData('',$RechargeModel->getError(),Config::get('code.tipsCode'));
            }
            $message = $YunClass->createRech2($user_info['bizUserId'],$order);
            if($message['status'] != 'OK'){
                outPutData('',$message['message'],Config::get('code.tipsCode'));
            }
            $signedValue = json_decode($message['signedValue'],true);
            $RechargeModel -> where(['order'=>$signedValue['bizOrderNo']])->update(['status'=>1,'orderNo'=>$signedValue['orderNo']]);
            $payClass = new YunPay();
            $url = $payClass->surePay($user_info['bizUserId'],$signedValue['bizOrderNo']);
            outPutData(array('url'=>$url,'msg'=>'即将跳转'));
        }
    }

    /**
     * 获取资金明细
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getCashFlow(Request $request){
        $PutModel = new Putlog();
        $user_info = $request->user_info;
        $param = $request->param();
        if (empty($param['curpage'])) {
            $curpage = 1;
        } else {
            $curpage = $param['curpage'];
        }
        if($param['type']>0){
            $where['type'] = $param['type'];
        }
        $where['uid']= $user_info['id'];
        $field = '*,FROM_UNIXTIME(create_time) as time';
        $dataList = $PutModel->where($where)->field($field)->order("id DESC")->select();
        $dataList = empty($dataList)?array():$dataList->toArray();
        $total_count = count($dataList);
        $total_page = ceil($total_count/self::PERPAGE);
        $data_list = pageArray($dataList,self::PERPAGE,$curpage);
        if(count($dataList)){
            foreach($dataList as &$v){
                $v['type_show'] = $this->getTypeAttr($v['type']);
            }
        }
        outPutData(array('list'=>$data_list,'total_page'=>$total_page,'total_count'=>$total_count));
    }


    /**
     * 提现申请
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getCash(Request $request){
        if(request()->isPost()){
            $user_info = $request->user_info;
            $param = $request->param();
            $CashModel = new Getcash();
            $CardModel = new Card();
            $mModel = new Members();
            $money = $param['money'];
            $MemberInfo = $mModel->where(['id'=>$user_info['id']])->find();
            if(empty($MemberInfo['pay_password'])){
                outPutData('','未设置支付密码',Config::get('code.tipsCode'));
            }
            if(!password_verify($param['pay_password'],$MemberInfo['pay_password'])){
                outPutData('','支付密码不正确',Config::get('code.tipsCode'));
            }
            if($money<confv('min-getcash')){
                outPutData('','提现金额不能少于'.confv('min-getcash'),Config::get('code.tipsCode'));
            }
            if($MemberInfo['money']<$money){
                outPutData('','超过可提现额度',Config::get('code.tipsCode'));
            }
            $CardInfo = $CardModel->where(['user_id'=>$user_info['id'],'id'=>$param['bank_id']])->find();
            $order = [
                'user_id' => $user_info['id'],
                'mobile'  => $CardInfo['bank_mobile'],
                'money'	  => $money,
                'fee'	  => confv('fee2'),
                'order'	  => 'GT'.create_order(),
                'card_id' => $param['bank_id'],
                'status'  => 0,
                'bankCardNo' => $CardInfo['bank_number'],
                'date'	  => date('Y-m-d H:i:s')
            ];

            $res = $CashModel->allowField(true)->save($order);
            if(!$res){
                outPutData('',$CashModel->getError(),Config::get('code.tipsCode'));
            }
            $msg = $mModel->where(['id'=>$user_info['id']])->update(['money'=>$MemberInfo['money']-$money]);
            if(!$msg){
                outPutData('',$mModel->getError(),Config::get('code.tipsCode'));
            }
            $logModel = new Putlog();
            $log = [
                'uid' => $user_info['id'],
                'money' => -$money,
                'type'	=> 5, //提现
                'order'	=> 'OD'.create_order(),
                'status' => 1,
                'crate_time' => time()
            ];
            $logModel->allowField(true)->save($log);
            outPutData(array('msg'=>'提交成功,提现金额待后台审核通过后打入银行卡!'));
        }
    }


    /**
     * 获取会员项目列表
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
    public function getMemberProjectList(Request $request){
        if($request->isPost()){
            $pModel = new Project();
            $user_info = $request->user_info;
            $param = $request->param();
            $where['p.status'] = ['neq',6];  //未结算状态
            $where['or.uid'] = $user_info['id'];
            if(intval($param['status'])>1){
                $where['p.status'] = ['eq',6];
            }
//            $where['p.id']= ['<',53];
            if (empty($param['curpage'])) {
                $curpage = 1;
            } else {
                $curpage = $param['curpage'];
            }
            $dataList = $pModel->getMemberProjectList($where);
            $total_count = count($dataList);
            $total_page = ceil($total_count/self::PERPAGE);
            $data_list = pageArray($dataList,self::PERPAGE,$curpage);
            if(count($data_list)){
                foreach($data_list as &$v){
                    $v['percent'] = GetProjectBar($v['project_id'],1);  //项目进度百分比
                }
            }
            outPutData(array('list'=>$data_list,'total_page'=>$total_page,'total_count'=>$total_count));
        }
    }


    /**
     * 会员搜索项目
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * @return array
     */
     public function searchMemberProject(Request $request){
         if($request->isPost()){
             $pModel = new Project();
             $user_info = $request->user_info;
             $param = $request->param();
             $where['or.status'] = ['egt',2];  //结算状态
             $where['or.uid'] = $user_info['id'];
             if(!empty($param['search_key'])){
             $where['p.project_name']=['like','%'. trim($param['search_key'].'%')];
             }
             if (empty($param['curpage'])) {
                 $curpage = 1;
             } else {
                 $curpage = $param['curpage'];
             }
             $dataList = $pModel->getMemberProjectList($where);
             $total_count = count($dataList);
             $total_page = ceil($total_count/self::PERPAGE);
             $data_list = pageArray($dataList,self::PERPAGE,$curpage);
             if(count($data_list)){
                 foreach($data_list as &$v){
                     $v['percent'] = GetProjectBar($v['project_id'],1);  //项目进度百分比
                 }
             }
             outPutData(array('list'=>$data_list,'total_page'=>$total_page,'total_count'=>$total_count));
         }
     }


    /**
     * 获取资金类型
     * @param $value
     * @author hey_heyang(635870453@qq.com)
     * @return string
     */
    public function getTypeAttr($value){
        switch ($value){
            case 1:
                $typename = '消费';
                break;
            case 2:
                $typename = '充值';
                break;
            case 3:
                $typename = '退还';
                break;
            case 4:
                $typename = '结算';
                break;
            default:
                $typename = '提现';
        }
        return $typename;
    }

    /**
     * 获取评估类型名称
     * @param $score
     * @author hey_heyang(635870453@qq.com)
     * @return string
     */
    private function getLookName($score){
        $name = Db::table('tf_rank')->where(['points'=>['>=',$score]])->order('points asc')->limit(1)->value('rankname');
        return $name;
    }

    /**
     * 我的银行卡
     * @author kangyi(997032813@qq.com)
     */
    public function card(Request $request){
        $CardModel = new Card();
        $user_info = $request->user_info;;
        $dataList = $CardModel->field('id,user_id,bank_name,bank_number,bank_mobile,bank_address,date,tranceNum,transDate,bankCode,cardType,status')->where(['user_id'=>$user_info['id'],'status'=>1,'cardType'=>['neq',2]])->order("id DESC")->select();
        foreach ($dataList as $key=>$val){
//            $dataList[$key]['bank_number'] = substr_replace($val['bank_number'],'********',4,11);
            $dataList[$key]['bank_number'] = substr($val['bank_number'],0,4).'******'.substr($val['bank_number'],-4,4);
            ;
        }
        $data = ['list'=>$dataList];
        outPutData($data);
    }

    /**
     * 新增银行卡
     * @author kangyi(997032813@qq.com)
     */
    public function addCard(Request $request){

        if(request()->isPost()){
            $user_info = $request->user_info;
            $YunClass = new Yunst();
            $CardModel = new Card();
            $data = input('post.');
            $info = [];
            if($data['card_type'] == 2){
//                $info['validate'] = $data['validate'];
//                $info['cvv2'] = $data['cvv2'];
                outPutData('','系统已禁止信用卡使用！',Config::get('code.error'));
            }
            $mModel = new Members();
            $MemberInfo = $mModel->where(['id'=>$user_info['id']])->find();
            $res = $YunClass->bindCard($user_info['bizUserId'],$data['bank_number'],$data['bank_mobile'],$MemberInfo['username'],$MemberInfo['certificate'],$info);
            $data['date'] = date('Y-m-d H:i:s');
            if($res['status'] == 'OK'){
                unset($data['card']);
                unset($data['card_type']);
                $signedValue = json_decode($res['signedValue'],true);
                $data['user_id'] = $user_info['id'];
                $data['bank_truename'] = $MemberInfo['username'];
                $data['tranceNum'] = $signedValue['tranceNum']; //流水号
                $data['transDate'] = $signedValue['transDate'] ? $signedValue['transDate'] : date('Ymd'); //申请时间
                $data['bank_name'] = $signedValue['bankName']; //银行名称
                $data['bankCode'] = $signedValue['bankCode']; //银行代码
                $data['cardType'] = $signedValue['cardType']; //类型
                $InsetId = $CardModel->insertGetId($data);
                if ($InsetId) {
                    outPutData(['id'=>$InsetId],'',Config::get('code.success'));
                }
            }elseif($res['errorCode']=='9000'){
                outPutData('',$res['message'],Config::get('code.error'));
            }else{
                outPutData('',$res['message'],Config::get('code.error'));
            }
        }
    }

    /**
     * 确认绑定银行卡
     * @author kangyi(997032813@qq.com)
     */
    public function actCard(Request $request){

        if(request()->isPost()){
            $user_info = $request->user_info;
            $YunClass = new Yunst();
            $CardModel = new Card();
            $id = input('post.id');
            $code = input('post.code');

            $CardInfo = $CardModel->where(['id'=>$id,'user_id'=>$user_info['id']])->find();
            if(empty($CardInfo)){
                outPutData('','绑定失败',Config::get('code.error'));
            }
            $res = $YunClass->ActbindCard($user_info['bizUserId'],$CardInfo,$code);
            $res['date'] = date('Y-m-d H:i:s');
            if($res['status'] == 'OK'){
                $reqult = $CardModel->where(['id'=>$id])->update(['status'=>1]);
                if ($reqult) {
                    outPutData('','绑定成功',Config::get('code.success'));
                }
            }else{
                outPutData('',$res['message'],Config::get('code.error'));
            }
        }
    }

    /**
     * 删除银行卡
     * @author kangyi(997032813@qq.com)
     */
    public function delCard(Request $request){


        if(request()->isPost()){
            $user_info = $request->user_info;
            $YunClass = new Yunst();
            $CardModel = new Card();
            $id = input('post.id');
            $CardInfo = $CardModel->where(['id'=>$id,'user_id'=>$user_info['id']])->find();
            if(empty($CardInfo)){
                outPutData('','删除失败',Config::get('code.error'));

            }

            if($CardInfo->getData('status') == 0){
                $res = $CardModel->where(['id'=>$id,'user_id'=>$user_info['id']])->delete();
                if($res){
                    outPutData('','删除成功',Config::get('code.success'));
                }else{
                    outPutData('',$CardModel->getError(),Config::get('code.error'));
                }
            }

            $res = $YunClass->unbindCard($user_info['bizUserId'],$CardInfo['bank_number']);
            if($res['status'] == 'OK'){
                $CardModel->where(['id'=>$id,'user_id'=>$user_info['id']])->delete();
                outPutData('','解绑成功',Config::get('code.success'));
            }else{
                outPutData('',$res['message'],Config::get('code.error'));
            }
        }
    }


    /**
     *wap个人上传头像
     * @param Request $request
     * @author hey_heyang(635870453@qq.com)
     * return array
     */
    public function logoUpload(Request $request)
    {
        if (request()->isPost()) {
            $user_info = $request->user_info;;
            $file = request()->file('imgFile');
            if ($file) {
                $dir = 'headimg';
                $upload_res = companyUpload($file, $dir);
                $upload_res['fileName'] = str_replace('\\', '/', $upload_res['fileName']);
                if ($upload_res['status']) {
                    $mModel = new Members();
                    $res_data['logo'] = $upload_res['fileName'];
                    $res_data['logoSrc'] = '/uploads/headimg/' . $upload_res['fileName'];
                    $res=$mModel->where(array('id'=>$user_info['id']))->update(array('head_thumb'=>$res_data['logoSrc']));
                    if(!$res){
                        outPutData('','上传失败',Config::get('code.tipsCode'));
                    }
                    $redis = Redis::instance();
                    $token = $redis->get('front_user:' . $user_info['id']);
                    $user_info['modify'] = true;
                    $redis->hSet('user_info', $token, json_encode($user_info));
                    outPutData($res_data,'上传成功',Config::get('code.success'));
                } else {
                    outPutData('','上传失败',Config::get('code.tipsCode'));
                }

            } else {
                outPutData('','请选择文件',Config::get('code.tipsCode'));
            }
        }
    }


    /**
     * 电子协议
     * @author kangyi(997032813@qq.com)
     */
    public function wapQianYue(Request $request){
        if(request()->isPost()){
            $user_info = $request->user_info;
            $mModel = new Members();
            $my_data = $mModel->where(array('id'=>$user_info['id']))->field('bizUserId')->find()->toArray();
            $YunClass = new Yunst();
            $url = $YunClass->wapQianYue($my_data['bizUserId']);
            outPutData($url,'',Config::get('code.success'));
        }
    }

    /**
     * 查询充值订单状态
     * @author hey_heyang(635870453@qq.com)
     */
    public function queryOrderState(Request $request){
        if(request()->isPost()){
            $model = new Recharge();
            $mModel = new Members();
            $user_info = $request->user_info;
            $param = $request->param();
            if(empty($param['order_sn'])){
                outPutData('','订单号错误',Config::get('code.error'));
            }else{
                $order_info =$model->where(array('user_id'=>$user_info['id'],'order'=>trim($param['order_sn'])))->find();
                if(empty($order_info)){
                    outPutData('','未查询到充值订单信息',Config::get('code.error'));
                }else{
                    $YunClass = new Yunst();
                    $my_data = $mModel->where(array('id'=>$user_info['id']))->field('bizUserId')->find()->toArray();
                    $tl_order_info = $YunClass->getOrderInfo($my_data['bizUserId'],trim($param['order_sn']));
                    $res_data['status'] =$tl_order_info['orderStatus'];
                    if($res_data['status']==3){
                        outPutData($res_data,'充值失败',Config::get('code.success'));
                    }elseif($res_data['status']==4){
                        outPutData($res_data,'充值成功',Config::get('code.success'));
                    }else{
                        outPutData($res_data,'充值进行中',Config::get('code.success'));
                    }
                }
            }
        }
    }


}
